package org.jeecg.modules.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DySmsEnum;
import org.jeecg.common.util.DySmsHelper;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.entity.RunnerMatch;
import org.jeecg.modules.entity.RunnerMatchInfo;
import org.jeecg.modules.entity.RunnerMatchPlayer;
import org.jeecg.modules.service.IRunnerMatchInfoService;
import org.jeecg.modules.service.IRunnerMatchPlayerService;
import org.jeecg.modules.service.IRunnerMatchService;
import org.jeecg.modules.system.util.SecurityUtil;
import org.jeecg.modules.utill.MqttUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author tanxy
 * @date 2022年11月28日 20:46
 */
@Slf4j
@RestController
@RequestMapping("/match")
public class MatchDeviceController {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IRunnerMatchService runnerMatchService;
    @Autowired
    private IRunnerMatchPlayerService playerService;
    @Autowired
    private IRunnerMatchInfoService infoService;

    @PostMapping("/start/{id}")
    public Result startMatch(@PathVariable("id") String id){
        log.info("比赛ID = "+id);
        //获取当前登录用户id
        LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        boolean status = runnerMatchService.updateMatchStatus(id, "jxz");
        if(status){
            RunnerMatch runnerMatch = runnerMatchService.getById(id);
            String matchtype = runnerMatch.getMatchtype();
            if(StrUtil.isNotEmpty(matchtype)){
                MqttUtil.RUNNER_TYPE_MAP.put(userId,matchtype);
            }
            MqttUtil.MATCH_TYPE_MAP.put(userId,0);
            MqttUtil.start(userId,id);
            return Result.ok();
        }
        return Result.error("已有比赛进行中...");
    }

    @PostMapping("/stop/{id}")
    public Result stopMatch(@PathVariable("id") String id){
        boolean status = runnerMatchService.updateMatchStatus(id, "yjs");
        if(status){
            LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();
            String userId = user.getId();
            MqttUtil.stop(userId,id);
            return Result.ok();
        }
        return Result.error("数据库错误");
    }


    @PostMapping("/startCall")
    public Result startCall(){

        LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        Integer matchType = MqttUtil.MATCH_TYPE_MAP.get(userId);
        if(matchType==2){
            return Result.error("比赛进行中，禁止检录操作！");
        }
        String matchId = MqttUtil.MATCH_MAP.get(userId);
        MqttUtil.startSatus(1,userId,matchId);
        return Result.ok();
    }

    @PostMapping("/stopCall")
    public Result stopCall(){

        LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        Integer matchType = MqttUtil.MATCH_TYPE_MAP.get(userId);
        String matchId = MqttUtil.MATCH_MAP.get(userId);

        if(matchType==2){
            return Result.error("比赛进行中，禁止检录操作！");
        }
        MqttUtil.startSatus(0,userId,matchId);
        return Result.ok();
    }

    @GetMapping("/canCall")
    public Result canCall(){

        LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        Integer matchType = MqttUtil.MATCH_TYPE_MAP.get(userId);
        String matchId = MqttUtil.MATCH_MAP.get(userId);

        return Result.ok(matchType==0?false:true);
    }


    @GetMapping("/callInfo/{ringcode}")
    public Result callInfo(@PathVariable("ringcode") String ringcode){
        //获取当前用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = loginUser.getId();
        String matchId = MqttUtil.MATCH_MAP.get(userId);
        if(StrUtil.isEmpty(matchId)){
            log.error("当前登录用户，没有开始的比赛!");
            return Result.error("当前登录用户，没有开始的比赛!");
        }
        RunnerMatchPlayer player = playerService.selectByRingCode(matchId, ringcode);

        return player==null?Result.error("芯片查无此人"):Result.ok(player);
    }
    /**
     * 开始记录比赛
     * @author tanxy
     * @date 2022/12/6 14:10
     * @return org.jeecg.common.api.vo.Result
     */
    @PostMapping("/startMatch/{id}")
    public Result startMatchRecord(@PathVariable("id") String id){
        LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();

        MqttUtil.startSatus(2,userId);
        return Result.ok();
    }

    @PostMapping("/stopMatch/{id}")
    public Result stopMatchRecord(@PathVariable("id") String id){
        LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        MqttUtil.startSatus(0,userId);
        return Result.ok();
    }

    @PostMapping("/device/status")
    public Result enhanceJavaListHttp(@RequestBody JSONObject params){
        log.info(" =========================================================== ");
        log.info("params: " + params.toJSONString());
        log.info("params.tableName: " + params.getString("tableName"));
        log.info(" =========================================================== ");
        JSONArray dataList = params.getJSONArray("dataList");
        for(int i =0;i<dataList.size();i++){
            JSONObject jsonObject = dataList.getJSONObject(i);
            String deviceCode = jsonObject.getString("device");
            if(StrUtil.isNotEmpty(deviceCode)){
                Object status = redisUtil.get(deviceCode);
                if(ObjectUtil.isNotEmpty(status)){
                    jsonObject.put("devicestatus",status);
                }else {
                    jsonObject.put("devicestatus","停止");
                }
            }
        }
        log.info("params.dataList: " + dataList);
        Result<Object> result = Result.OK(dataList);
        result.setCode(1);
        return result;
    };

    /**
     * 开始组比赛
     * @author tanxy
     * @date 2022/12/14 22:59
     * @param id 
     * @return org.jeecg.common.api.vo.Result
     */
    @PostMapping("/startGroup/{id}")
    public Result startGroup(@PathVariable("id") String id){

        LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        String matchId = MqttUtil.MATCH_MAP.get(userId);

        if(StrUtil.isEmpty(matchId)){
            return Result.error("请开始一场比赛.");
        }

        MqttUtil.MATCH_TYPE_MAP.put(userId,2);
        //记录比赛开启
        MqttUtil.startSatus(2,userId,matchId);

        String[] splitIds = id.split(",");

        Date startDate = Calendar.getInstance().getTime();

        for(String tempId:splitIds){
            RunnerMatchInfo groupInfo = infoService.getById(tempId);
            UpdateWrapper<RunnerMatchPlayer> playerUpdateWrapper = new UpdateWrapper<>();
            playerUpdateWrapper.eq("matchid",matchId).eq("groupid",groupInfo.getMgroup());
            RunnerMatchPlayer player = new RunnerMatchPlayer();
            player.setPstarttime(startDate);
            boolean update = playerService.update(player, playerUpdateWrapper);
            if(update){
                List<String> groupids = MqttUtil.MATCH_GROUPID_MAP.get(userId);
                if(ObjectUtil.isEmpty(groupids)){
                    groupids = new ArrayList<>();
                    MqttUtil.MATCH_GROUPID_MAP.put(userId,groupids);
                }
                groupids.add(groupInfo.getMgroup());
                groupInfo.setMstarttime(startDate);
                infoService.updateById(groupInfo);
            }else{
                log.error("数据库错误！");
                return Result.error("数据库错误!");
            }
        }
        return Result.ok();
    }


    @PostMapping("/sms/{id}")
    public Result sms(@PathVariable("id") String id){
        List<RunnerMatchPlayer> players = playerService.selectByMainId(id);
        for(RunnerMatchPlayer player:players){
            String phone = player.getPhone();
            if(StrUtil.isNotEmpty(phone)){
                JSONObject obj = new JSONObject();
                obj.put("code", player.getPcode());
                obj.put("name", player.getPlayer());
                try {
                    DySmsHelper.sendSms(phone,obj, DySmsEnum.MATCH_NOTICE_TEMPLATE_CODE);
                    log.info("短信发送成功,选手："+player.getPlayer());
                } catch (ClientException e) {
                    log.error("短信发送失败，选手:"+player.getPlayer());
                }
            }else{
                log.error("短信发送失败，没有维护选手手机号，选手:"+player.getPlayer());
            }
        }
        return Result.ok();
    }

}
